package com.zz.shop.web.controller;

import com.alibaba.fastjson.JSON;
import com.zz.shop.common.Const;
import com.zz.shop.common.ResponseCode;
import com.zz.shop.common.ResponseResult;
import com.zz.shop.entity.User;
import com.zz.shop.service.UserService;
import com.zz.shop.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/user")
public class UserController extends BaseServlet {
    private UserService us = new UserServiceImpl();

    public String checkName(HttpServletRequest request, HttpServletResponse response) {
        String uname = request.getParameter("username");
        //访问业务层
        ResponseResult result = us.findUserByName(uname);
        String s = JSON.toJSONString(result);

        return s;
    }
    public String reg(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        User u=new User();
        BeanUtils.populate(u,parameterMap);
        ResponseResult rr=us.reg(u);
        if (rr.getCode()== ResponseCode.SUCCESS.getCode()) {
            return Const.REDIRECT+"/registerSuccess.jsp";
        }
        request.setAttribute(Const.MSG,rr);
        return Const.FORWARD+Const.MESSAGE;
    }
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        ResponseResult rr = us.doLogin(username,password);
        if (rr.getCode()== ResponseCode.SUCCESS.getCode()) {
            //保存数据到session中
            request.getSession().setAttribute(Const.LOGIN_INFO,rr.getT());
            //直接重定向到首页
            return Const.REDIRECT+"/index.jsp";
        }
        request.setAttribute("msg", rr);
        return Const.FORWARD+"login.jsp";
    }
}
